﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Profile;
using Gift.DAL;
using Gift.Model;
using Gift.Utile;

using System.Text;

namespace WebSite.cn
{
    public partial class order : BasePage
    {
        // Fields
        public string address1 = "";
        public string payDescription = "";
        public string cardprice = "0";
        public string carmsg = "";
        public string cname = "";
        public string cname1 = "";
        public string content = "";
        public string email = "";
        public string email1 = "";
        public string ocard = "";
        public string ocode = "";
        public string content1 = "";
        public string omsg = "";
        public string omsg1 = "";
        public string opay = "";
        public string orderscore = "0";
        public string oscore = "";
        public string oship = "";
        public string otime = "";

        public string phone = "";
        public string phone1 = "";
        public string post1 = "";
        public string scoremsg = "未使用积分";

        public string tel = "";
        public string tel1 = "";
        public string totalprice = "0";
        public string ordercode = "";
        public string remainprice = "0";
        public string shopprice = "0";
       


        public string sendDate = "";

        readonly OrderAccount theOrderAccount = new OrderAccount();
        readonly MemberAccount theMemberAccount = new MemberAccount();
        readonly Member theMember = new Member();

        decimal _payMoneyByCard = 0;
        decimal _payMoneyByOther = 0;


        private decimal PayMoneyByCard
        {
            get {
                if (_payMoneyByCard > 0)
                {
                    return _payMoneyByCard;
                }
                else
                {
                    if (!string.IsNullOrEmpty(base.Request.Form["cardpaymoney"]))
                    {
                        _payMoneyByCard = decimal.Parse(base.Request.Form["cardpaymoney"]);
                        return _payMoneyByCard;
                    }
                    else
                    {
                        return 0;
                    }
                }
            }
            set {
                _payMoneyByCard = value;
            }
        }

        private decimal PayMoneyByOther
        {
            get {
                if (_payMoneyByOther > 0)
                {
                    return _payMoneyByOther;
                }
                else
                {
                    if (!string.IsNullOrEmpty(base.Request.Form["paymoney"]))
                    {
                        _payMoneyByOther = decimal.Parse(base.Request.Form["paymoney"].ToString());
                        return _payMoneyByOther;
                    }
                    else
                    {
                        return 0;
                    }
                }

            }
            set
            {
                _payMoneyByOther = value;
            }
        }

      
        void InitReseiveClient()
        {
            if (Request.Form["chk1"] == "1")
            {
                cname1 = Request.Form["cname"];
                email1 = Request.Form["email"];
                omsg1 = Request.Form["omsg"];
                phone1 = Request.Form["phone"];
                content1 = Request.Form["content"];
                post1 = Request.Form["post"];
                tel1 = Request.Form["tel"];
                address1 = Request.Form["AddressArea1$ddlProvence"] + "," + Request.Form["AddressArea1$ddlCity"] + "," + Request.Form["address"];
            }
            else
            {
                cname1 = Request.Form["cname1"];
                email1 = Request.Form["email1"];
                omsg1 = Request.Form["omsg1"];
                phone1 = Request.Form["phone1"];
                content1 = Request.Form["content1"];
                post1 = Request.Form["post1"];
                tel1 = Request.Form["tel1"];
                address1 =  Request.Form["address1"];
            }
            sendDate = Request.Form["senddate"];
            if (string.IsNullOrEmpty(sendDate))
            {
                sendDate = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd");
            }

            if(string.IsNullOrEmpty(cname1))
            {
                   base.Response.Write("<script language=javascript>window.location.href='index.aspx';</script>");
                    base.Response.End();
            }
        }

        // Methods
        private void PayByCardInAccount()
        {
            this.InitReseiveClient();
            string sOrderID = Request.Form["ordercode"];
            string strOrderCode = Request.Form["ordercode"];
            this.totalprice = base.Request.Form["totalprice"];

            string sCardCodes = "";
            decimal dTotalCardPrice = 0;   
                   
            string sPay = "15";

            string sUpdateCard = string.Empty;
            string totalscore = string.Empty;  
                totalscore = "0";
                this.tdTotal.Visible = false;

                StringBuilder strInsertOrderAccount = new StringBuilder();
                if (this.LoginUserMember.DicUserCardList != null)
                {

                        foreach (dbCard card in this.LoginUserMember.DicUserCardList.Values)
                        {
                            dTotalCardPrice += card.cardprice;
                            sCardCodes += "'" + card.cardcode + "',";

                            strInsertOrderAccount.Append(" insert tbOrderAccount(OrderCode,CardId,CardAdded,AddDate) values('" + strOrderCode + "',"
                                                    + card.cardid.ToString() + ","
                                                    + "1,"
                                                    + "getdate());");
                        }

                    if (sCardCodes.Length > 0) sCardCodes = sCardCodes.Substring(0, sCardCodes.Length - 1); 
                    sUpdateCard = "update DB_Card set states = 2,closeTime = getdate() where cardcode in (" + sCardCodes + ");";
                    sUpdateCard = sUpdateCard + strInsertOrderAccount.ToString();
                }

                string sSQLUpdateShoppro = " if exists( select 1 from  tbGoodsFrozen where goodsId in ( select  productid from DB_Car where  carid in(" + base.Request.Form["carid"] + ") and isnull(db_Car.professionAreaName,'') = ''))"
                                        + " begin "
                                        + " update tbGoodsFrozen set frozenCount = isnull(frozenCount,0) + db_car.pronum  from tbGoodsFrozen,db_Car where tbGoodsFrozen.goodsId = db_car.productid and isnull(db_Car.professionAreaName,'') = '' and db_Car.carid in(" + base.Request.Form["carid"] + ") "
                                        + " end else begin "
                                        +" insert into tbGoodsFrozen(goodsId,frozenCount) select  productid,pronum from DB_Car where  carid in(" + base.Request.Form["carid"] + ") and isnull(db_Car.professionAreaName,'') = ''"
                                        +" end ;"
                             + " update DB_Shoppro  set proku1= isnull(proku1,0) - db_Car.pronum,  saleCount = isnull(saleCount,0) + db_Car.pronum "
                             + " from DB_Shoppro,db_Car "
                             + " where DB_Shoppro.proid = db_Car.productid and isnull(db_Car.professionAreaName,'') = '' and db_Car.carid in(" + base.Request.Form["carid"] + ") ;"
                              + " update DB_Car set flag=1,orderid=" + sOrderID + "  where carid in(" + base.Request.Form["carid"] + ") and isnull(db_Car.professionAreaName,'') = '';";

                string sMemberid = base.LoginUserMember.IsCard == true ? "0" : base.LoginUserMember.MemberId;
                  string sSQLUpdateOrder =  string.Concat(new object[] { 
                "insert into DB_Order (orderid,ordercode,memberid,pay,states,cname,tel,phone,post,address,email,content,cname1,tel1,phone1,post1,address1,email1,ordertime,sendDate,"
               + " totalprice,cardprice,scoreprice,cardid,orderscore,shopprice) values (", sOrderID, ",'", strOrderCode, "',", sMemberid, ",'", sPay, "',0,'", base.Request.Form["cname"], "','", base.Request.Form["tel"], "','", base.Request.Form["phone"], 
                "','", base.Request.Form["post"], "','", base.Request.Form["address"], "','", base.Request.Form["email"], "','", base.Request.Form["content"], "','", cname1, "','", tel1, "','", phone1, "','", post1, 
                "','", address1, "','", email1, "','", DateTime.Now, "','" + sendDate + "','", this.totalprice, "',", dTotalCardPrice, ",", 0, ",", "0", ",", totalscore, 
                "," + shopprice +")",sUpdateCard,";"
             });

                if (string.IsNullOrEmpty(sCardCodes)) sCardCodes = "'0'";
                if (Convert.ToDecimal(totalprice) != dTotalCardPrice)
                {
                    base.Response.Write("<script>alert('专区金额与专区商品价格不一致，购买失败！')</script>");
                    base.Response.Write("<script language=javascript>window.location.href='index.aspx';</script>");
                    base.Response.End();
                }
                int iResult = theMemberAccount.UserSpendMoney( Convert.ToDecimal(totalprice), sCardCodes,dTotalCardPrice.ToString(), sSQLUpdateShoppro + sSQLUpdateOrder);
               if (iResult == -2)
                {
                    base.Response.Write("<script>alert('专区金额与专区商品价格不一致，购买失败！')</script>");
                    base.Response.Write("<script language=javascript>window.location.href='index.aspx';</script>");
                    base.Response.End();
                }

         

            Response.Write("<script>('购买成功！')</script>");

            if (base.LoginUserMember.DicUserCardList != null)
            {
                base.LoginUserMember.DicUserCardList.Clear();
            }
            if (DicProductPrice != null)
            {
                DicProductPrice = null;
            }

            base.Response.Write("<script language=javascript>window.location.href='order.aspx?oid=" + sOrderID + "';</script>");
            base.Response.End();

          }

        private void PayByBankAccount()
        {
            this.InitReseiveClient();
            string sOrderID = Request.Form["ordercode"];
            string strOrderCode = Request.Form["ordercode"];
            this.totalprice = base.Request.Form["totalprice"];

            string sPay = "16";

            string sUpdateCard = string.Empty;
            string totalscore = string.Empty;
            totalscore = "0";
            this.tdTotal.Visible = false;

            StringBuilder strInsertOrderAccount = new StringBuilder();


            string sSQLUpdateShoppro = " update DB_Car set flag=0,orderid=" + sOrderID + "  where carid in(" + base.Request.Form["carid"] + ") and isnull(db_Car.professionAreaName,'') != '';";
            string sSQLUpdateOrder = string.Concat(new object[] { 
                "insert into DB_Order (orderid,ordercode,memberid,pay,states,cname,tel,phone,post,address,email,content,cname1,tel1,phone1,post1,address1,email1,ordertime,sendDate,"
               + " totalprice,cardprice,scoreprice,cardid,orderscore,shopprice) values (", sOrderID, ",'", strOrderCode, "',", base.LoginUserMember.MemberId, ",'", sPay, "',6,'", base.Request.Form["cname"], "','", base.Request.Form["tel"], "','", base.Request.Form["phone"], 
                "','", base.Request.Form["post"], "','", base.Request.Form["address"], "','", base.Request.Form["email"], "','", base.Request.Form["content"], "','", cname1, "','", tel1, "','", phone1, "','", post1, 
                "','", address1, "','", email1, "','", DateTime.Now, "','" + sendDate + "','", this.totalprice, "',", 0, ",", 0, ",", "0", ",", totalscore, 
                "," + 0 +")",sUpdateCard,";"
             });

            try
            {
                SQLAccess.DoSql(sSQLUpdateShoppro + sSQLUpdateOrder);
            }
            catch
            {
                base.Response.Write("<script>alert('下单失败！')</script>");
                base.Response.Write("<script language=javascript>window.location.href='account.aspx';</script>");
                base.Response.End();
            }

            Response.Write("<script>('下单成功！')</script>");

            if (DicProductPrice!= null)
            {
                DicProductPrice = null;
            }

            base.Response.Write("<script language=javascript>window.location.href='order.aspx?type=shop&oid=" + sOrderID + "';</script>");
            base.Response.End();

        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!base.IsPostBack)
            {
               string str = base.Request.Form["action"];
               if (str == "add")
              {
                  if (base.LoginUserMember != null  && base.LoginUserMember.DicUserCardList != null && base.LoginUserMember.DicUserCardList.Count > 0)
                  {
                     
                      this.PayByCardInAccount();
                  }
                  else if (base.LoginUserMember != null && base.ShopProductPrice != 0)
                  {

                      this.PayByBankAccount();
                  }
                  else
                  {
                      base.Response.Write("<script language=javascript>alert('购买失败！操作时间过期，请重新登录购买！');window.location.href='ProfessionArea.aspx?sid=2';</script>");
                      base.Response.End();
                  }
              }
               else if (base.Request.QueryString["oid"] != null || base.Request.QueryString["code"] != null)
                {
                    this.BindForm();
                }
                else
                {
                    base.Response.Write("<script language=javascript>window.location.href='index.aspx';</script>");
                    base.Response.End();
                }
            }
          }


        

      

        private void BindForm()
        {
            remainprice = "0";
            totalprice = "0";
            shopprice = "0";
            cardprice = "0";
            DataTable table;
            DataTable table2;

            string sWhere = string.Empty;
            if (Request.QueryString["oid"] != null)
            {
                sWhere = "  orderid=" + base.Request.QueryString["oid"];
            }
            else
            {
                sWhere = "  ordercode=" + base.Request.QueryString["code"];
            }
            table = SQLAccess.GreatDs("select orderid,ordercode,pay,ship,cname,tel,phone,post,address,email,content,cardprice,scoreprice,cname1,cardid,orderscore,tel1,phone1,post1,address1,email1,content1,ordertime,sendDate,totalprice,shopprice from DB_Order where " + sWhere + "").Tables[0];
            if (table.Rows.Count > 0)
            {
                this.ocode = table.Rows[0]["ordercode"].ToString();
                totalprice = table.Rows[0]["totalprice"].ToString();
                shopprice = table.Rows[0]["shopprice"].ToString() == string.Empty ? "0" :table.Rows[0]["shopprice"].ToString();
                this.otime = table.Rows[0]["ordertime"].ToString();
                this.cardprice = table.Rows[0]["cardprice"].ToString();
                this.orderscore = table.Rows[0]["orderscore"].ToString();
                this.omsg = "姓 名 : " + table.Rows[0]["cname"].ToString() + "<br />联系电话 : " + table.Rows[0]["tel"].ToString() + "<br />手 机 :" + table.Rows[0]["phone"].ToString() + "<br /> ";
                this.omsg1 = "姓 名 : " + table.Rows[0]["cname1"].ToString() + "<br />收货地址 : " + table.Rows[0]["address1"].ToString() + "<br />联系电话 : " + table.Rows[0]["tel1"].ToString() + "<br />手 机 : " + table.Rows[0]["phone1"].ToString() + "<br />送货时间 :" + table.Rows[0]["senddate"].ToString() + "<br />";
                this.content1 = table.Rows[0]["content1"].ToString();
                table2 = SQLAccess.GreatDs("select payname,pay,paycontent from DB_Pay where payid in (" + table.Rows[0]["pay"].ToString() + ")").Tables[0];
                this.opay = "<ul>";
                if (table2.Rows.Count > 0)
                {
                    this.opay = this.opay + "<li>" + table2.Rows[0][0].ToString() + "<br/>" + table2.Rows[0][2].ToString() + "</li>";
                }
                this.opay = this.opay + "</ul>";

                string sType = "1";
                if (Request.QueryString["type"] == "shop")
                {
                    sType = "0";
                }
                table2 = SQLAccess.GreatDs("select DB_Car.carid,DB_Car.pronum,DB_Car.price,DB_Car.sumprice,DB_Car.contents,DB_Shoppro.typeid,DB_Shoppro.proname,DB_Shoppro.proprice1,DB_Shoppro.propic2,DB_Shoppro.proid  from DB_Car inner join DB_Shoppro on DB_Car.productid=DB_Shoppro.proid where DB_Car.flag=" + sType + " and DB_Car.orderid=" + table.Rows[0]["orderid"].ToString() + "").Tables[0];
                if (table2.Rows.Count > 0)
                {
                    foreach (DataRow row in table2.Rows)
                    {
                        this.carmsg = this.carmsg + "<tr>";
                        string carmsg = this.carmsg;
                        this.carmsg = carmsg + "<td bgcolor='#FFFFFF'><a href='products_details.aspx?tid=" + row["typeid"].ToString() + "&pid=" + row["proid"].ToString() + "' target=_blank><img src='../uploadfile/product/" + row["propic2"].ToString() + "' align='left' border='0' width='106px' /></a></td>";
                        string str11 = this.carmsg;
                        this.carmsg = str11 + "<td bgcolor='#FFFFFF'><a href='products_details.aspx?tid=" + row["typeid"].ToString() + "&pid=" + row["proid"].ToString() + "' class='blue' target=_blank>" + row["proname"].ToString() + "</a><br /><br/>" + row["contents"].ToString() + "</td>";
                        this.carmsg = this.carmsg + "<td bgcolor='#FFFFFF'>" + string.Format("{0:f}", row["price"]) + "元</td>";
                        this.carmsg = this.carmsg + "<td bgcolor='#FFFFFF'>" + row["pronum"].ToString() + "</td>";
                        this.carmsg = this.carmsg + "<td bgcolor='#FFFFFF'>" + string.Format("{0:f}", row["sumprice"]) + " 元</td>";
                        this.carmsg = this.carmsg + "</tr>";
                    }
                }

                this.remainprice = string.Format("{0:f}", (decimal.Parse(this.totalprice) - decimal.Parse(this.cardprice) - decimal.Parse(this.shopprice)));
                //this.payDescription = "卡支付：" + string.Format("{0:f}", this.cardprice) + "； 账户支付金额：" + string.Format("{0:f}", this.remainprice) + "<br/>";    
            }       
         }
    }
}




   